using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Ardal.MSBuildShellExtension.DomainModel.API;

/*
 * Copyright (c) 2007-2008, Thomas Ardal (thomasardalatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace Ardal.MSBuildShellExtension.Configurator
{
    public partial class EditorControl : UserControl
    {
        private readonly IList<IEditor> items;
        private IEditor currentSelected;

        public EditorControl()
        {
            items = new List<IEditor>();
            InitializeComponent();
            EventHandler argumentsContextMenuItemEventHandler = delegate(object sender, EventArgs args)
            {
                ToolStripMenuItem selectedItem = sender as ToolStripMenuItem;
                if (selectedItem != null)
                {
                   insertVariable(selectedItem.Text, argumentsTextBox);
                }
            };
            EventHandler filenameContextMenuItemEventHandler = delegate(object sender, EventArgs args)
            {
                ToolStripMenuItem selectedItem = sender as ToolStripMenuItem;
                if (selectedItem != null)
                {
                    insertVariable(selectedItem.Text, filenameTextBox);
                }
            };
            contextMenuStrip1.Items.Add(new ToolStripMenuItem(EditorVariableConstants.BuildFileVariable, null, argumentsContextMenuItemEventHandler));
            contextMenuStrip1.Items.Add(new ToolStripMenuItem(EditorVariableConstants.FileVariable, null, argumentsContextMenuItemEventHandler));
            contextMenuStrip1.Items.Add(new ToolStripMenuItem(EditorVariableConstants.ColumnVariable, null, argumentsContextMenuItemEventHandler));
            contextMenuStrip1.Items.Add(new ToolStripMenuItem(EditorVariableConstants.LineVariable, null, argumentsContextMenuItemEventHandler));
            contextMenuStrip2.Items.Add(new ToolStripMenuItem(EditorVariableConstants.ProgramFilesVariable, null, filenameContextMenuItemEventHandler));

            //Fill combobox with available templates
            foreach (IEditor editor in DomainModelFacade.Instance.Editors)
            {
                availableEditorsComboBox.Items.Add(editor);
            }

            //Set the default editor as selected item
            foreach (IEditor editor in availableEditorsComboBox.Items)
            {
                if (editor.DefaultEditor)
                {
                    availableEditorsComboBox.SelectedItem = editor;
                    break;
                }
            }

            //If no default editor is defined, select the first item instead
            if (availableEditorsComboBox.SelectedIndex == -1 && availableEditorsComboBox.Items.Count > 0)
            {
                availableEditorsComboBox.SelectedIndex = 0;
            }

            //Set focus on New button if no editors have been specified
            if (availableEditorsComboBox.Items.Count == 0)
            {
                newButton.Focus();
            }
        }

        private void variablesButton_Click(object sender, EventArgs e)
        {
            contextMenuStrip1.Show(argumentVariablesButton, new Point(0, argumentVariablesButton.Height));
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            currentSelected = null;
            StateController.ChangeState(new NewEditorState(this));
        }

        #region States
        private class NewEditorState : IState
        {
            private readonly EditorControl editorControl;

            public NewEditorState(EditorControl editorControl)
            {
                this.editorControl = editorControl;
            }
            #region IState Members

            public void Activate()
            {
                editorControl.titleTextbox.Clear();
                editorControl.titleTextbox.Enabled = true;
                editorControl.filenameTextBox.Clear();
                editorControl.filenameTextBox.Enabled = true;
                editorControl.argumentsTextBox.Clear();
                editorControl.argumentsTextBox.Enabled = true;
                editorControl.argumentVariablesButton.Enabled = true;
                editorControl.addButton.Enabled = true;
                editorControl.removeButton.Enabled = false;
                editorControl.titleTextbox.Focus();
                editorControl.defaultCheckBox.Checked = false;
            }

            #endregion
        }

        private class ShowEditorState : IState
        {
            private readonly EditorControl editorControl;
            private readonly IEditor editor;

            public ShowEditorState(EditorControl editorControl, IEditor editor)
            {
                this.editorControl = editorControl;
                this.editor = editor;
            }
            #region IState Members

            public void Activate()
            {
                editorControl.availableEditorsLabel.Enabled = true;
                editorControl.availableEditorsComboBox.Enabled = true;
                editorControl.titleTextbox.Text = editor.Title;
                editorControl.filenameTextBox.Text = editor.Filename;
                editorControl.argumentsTextBox.Text = editor.Arguments;
                editorControl.titleTextbox.Enabled = false;
                editorControl.argumentVariablesButton.Enabled = true;
                editorControl.addButton.Enabled = false;
                editorControl.removeButton.Enabled = true;
                editorControl.defaultCheckBox.Checked = editor.DefaultEditor;
            }

            #endregion
        }

        private class RemoveEditorState : IState
        {
            private readonly EditorControl editorControl;
            private readonly IEditor removedObject;

            public RemoveEditorState(EditorControl editorControl, IEditor removedObject)
            {
                this.editorControl = editorControl;
                this.removedObject = removedObject;
            }
            #region IState Members

            public void Activate()
            {
                editorControl.availableEditorsComboBox.Items.Remove(removedObject);
                if (editorControl.availableEditorsComboBox.Items.Count > 0)
                {
                    editorControl.availableEditorsComboBox.SelectedItem = editorControl.availableEditorsComboBox.Items[0];
                }
                else
                {
                    editorControl.availableEditorsComboBox.Text = "";
                    editorControl.availableEditorsLabel.Enabled = false;
                    editorControl.availableEditorsComboBox.Enabled = false;
                    editorControl.titleTextbox.Clear();
                    editorControl.defaultCheckBox.Enabled = false;
                    editorControl.filenameTextBox.Clear();
                    editorControl.argumentsTextBox.Clear();
                    editorControl.removeButton.Enabled = false;
                    editorControl.availableEditorsComboBox.Enabled = false;
                    editorControl.titleTextbox.Enabled = false;
                    editorControl.filenameTextBox.Enabled = false;
                    editorControl.argumentsTextBox.Enabled = false;
                    editorControl.openFileButton.Enabled = false;
                    editorControl.argumentVariablesButton.Enabled = false;
                    editorControl.defaultCheckBox.Checked = false;
                }

            }

            #endregion
        }
        #endregion

        private void addButton_Click(object sender, EventArgs e)
        {
            //Do error handling
            IEditor editor = DomainModelFacade.Instance.AddEditor(titleTextbox.Text, filenameTextBox.Text, argumentsTextBox.Text, defaultCheckBox.Checked);
            editor.Modified = true;
            items.Add(editor);
            availableEditorsComboBox.Items.Add(editor);
            availableEditorsComboBox.SelectedItem = editor;
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (availableEditorsComboBox.SelectedIndex != -1)
            {
                IEditor deletableItem = (IEditor)availableEditorsComboBox.Items[availableEditorsComboBox.SelectedIndex];
                deletableItem.Deleted = true;

                StateController.ChangeState(new RemoveEditorState(this, deletableItem));
            }
        }

        private void templateComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            IEditor editor = (IEditor)availableEditorsComboBox.SelectedItem;
            if (!editor.Deleted)
            {
                currentSelected = editor;
                StateController.ChangeState(new ShowEditorState(this, editor));
            }
        }

        private static void insertVariable(string variable, TextBoxBase target)
        {
            string text = target.Text;
            text = text.Insert(target.SelectionStart, variable);
            target.Text = text;
            target.Focus();
            target.SelectionStart = target.SelectionStart + variable.Length;
            target.SelectionLength = 0;
        }

        private void filenameTextBox_Validated(object sender, EventArgs e)
        {
            if (currentSelected != null)
            {
                if (!filenameTextBox.Text.Equals(currentSelected.Filename))
                {
                    currentSelected.Filename = filenameTextBox.Text;
                    currentSelected.Modified = true;
                }
            }
        }

        private void argumentsTextBox_Validated(object sender, EventArgs e)
        {
            if (currentSelected != null)
            {
                if (!argumentsTextBox.Text.Equals(currentSelected.Arguments))
                {
                    currentSelected.Arguments = argumentsTextBox.Text;
                    currentSelected.Modified = true;
                }
            }
        }

        private void defaultCheckBox_Validated(object sender, EventArgs e)
        {
            if (currentSelected != null)
            {
                currentSelected.DefaultEditor = defaultCheckBox.Checked;
                currentSelected.Modified = true;
            }
            if (defaultCheckBox.Checked)
            {
                foreach (IEditor editor in availableEditorsComboBox.Items)
                {
                    if (editor != currentSelected)
                    {
                        editor.DefaultEditor = false;
                        editor.Modified = true;
                    }
                }
            }
        }

        private void openFileButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filenameTextBox.Text = openFileDialog1.FileName;
            }
        }

        private void filenameVariablesButton_Click(object sender, EventArgs e)
        {
            contextMenuStrip2.Show(filenameVariablesButton, new Point(0, filenameVariablesButton.Height));
        }
    }
}
